package cn.com.callback

import groovy.json.*;
import groovy.swing.impl.DefaultAction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import cn.com.elite.EliteBean;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.wisdge.dataservice.Result;
import java.util.Map;
import java.util.Date;
import java.util.HashMap;
import cn.com.elite.Util;
import cn.com.kh.UcisXML;
import java.net.URLEncoder;

import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;

/**
 *
 * @Title: IVROBResult
 * @Description:外呼催缴任务结果查询接口
 * @author: Yuchieh 
 * @date 2021-03
 *
 */


public class IVROBResult implements ServiceBackInvoke{
	private static final Log log=LogFactory.getLog(IVROBResult.class);
	public String doCallBack(EliteBean eliteBean,HttpServletRequest request,HttpServletResponse response){
				
		response.setCharacterEncoding("UTF-8");
		JSONObject resulterror = new JSONObject();
		
		def obResultlist = eliteBean.chaxun_sql("SELECT COUNT(*) AS IDSUM FROM T_IVROBLog_New WHERE id IS NOT NULL AND result IS NULL","dataSource");
		def obmap = obResultlist[0];
		def idnum = obmap.get("IDSUM");
		
		log.debug("idnum:"+idnum);
		
		if(idnum<=0){
			resulterror.put("code", "-1");
			resulterror.put("msg", "未找到进行中外呼数据！");
			return  resulterror;
		}
		try{
			//获取电话号码
			def maplist2=eliteBean.chaxun_sql("SELECT  Timestamp,Sign,Id,type,sms_guid FROM T_IVROBLog_New WHERE id IS NOT NULL AND result IS NULL group by Timestamp,Sign,Id,type,sms_guid","dataSource");
				if(maplist2.size()>0){
					def Oblist;
					for(int i=0;i<maplist2.size();i++){
						//log.debug("maplist2[i]"+maplist2[i]);
						def curmap=maplist2[i];
						def obts = curmap.get("Timestamp");
						def obsign = curmap.get("Sign");
						def Type = curmap.get("type");
						def obid = curmap.get("Id");
						def sms_guid = curmap.get("sms_guid");
						
						Oblist = OBResult(obts,obsign,obid,Type,eliteBean,sms_guid);
					}
				return Oblist;
			}
			}catch(Exception e){
				resulterror.put("code", "-1");
				resulterror.put("msg", "接口异常！"+e);
				return  resulterror;
			}
	}
	public static String OBResult(String obts, String obsign, String obid,String Type,EliteBean eliteBean,String Sms_guid) {
		long startTime = System.currentTimeMillis();

		String reJson = null;
		try {
			
			String jsonString = "{\"ID\":\""+obid+"\",\"AppId\":\"crm\",\"Sign\":\""+obsign+"\",\"Timestamp\":\""+obts+"\"}";
			
			//json
			JSONObject ivrobj = new JSONObject(jsonString);
						
			log.debug("原始的json:" + ivrobj);
						
			//接口
			Map headMap = new HashMap();
			headMap.put("Content-Type","application/json");
			
			def charset="utf-8";
			def timeout=300000;
			def enablessLfag=0;

			//生产
			def url = "http://10.200.2.147/RDConnector/OutboundResult.html";
			//测试
			//def url = "http://10.200.2.151:8001/RDConnector/OutboundResult.html";
			log.debug("url="+url);

			//接口调用
			def jsonBack=Util.doHttpPostUseHead(url,jsonString,charset,timeout,enablessLfag,headMap);
			log.debug("jsonBack1:"+jsonBack);
			
			JSONObject inJson = new JSONObject(jsonBack);
			JSONArray info = inJson.getJSONArray("info");
			//log.debug("info:" + info);
			
			for(int i = 0; i<info.length();i++){
				startTime = System.currentTimeMillis();

				def phone = info.getJSONObject(i).get("phone");
				def result = info.getJSONObject(i).get("result");
				def result1	= info.getJSONObject(i).get("result1");
				def result1code	= info.getJSONObject(i).get("result1code");
				def firsttime = info.getJSONObject(i).get("firsttime");
				def result2	= info.getJSONObject(i).get("result2");
				def result2code	=info.getJSONObject(i).get("result2code");
				def secondtime =info.getJSONObject(i).get("secondtime");
				def result3 = info.getJSONObject(i).get("result3");
				def result3code =info.getJSONObject(i).get("result3code");
				def thirdtime =info.getJSONObject(i).get("thirdtime");
				def smstext = info.getJSONObject(i).get("text");
				def CallEndTime;
				def CurrentPhoneDialCount = 0;
				if(result1!="0"){
					CurrentPhoneDialCount = CurrentPhoneDialCount + 1;
				}
				if(result2!="0"){
					CurrentPhoneDialCount = CurrentPhoneDialCount + 1;
				}
				if(result3!="0"){
					CurrentPhoneDialCount = CurrentPhoneDialCount + 1;
				}
				if(thirdtime!=''){
					CallEndTime=thirdtime;
				};
				if(secondtime!=''){
					CallEndTime=secondtime;
				};
				if(firsttime!=''){
					CallEndTime=firsttime;
				}
				log.debug("result:" + result);
				if(result != "0") {
					if(Type == "A00011"){
						if(result == "1") {
							def updateRecord = "update T_IVROBRecord set status = 2,OBResult = '3001',CurrentPhoneDialCount = '"+CurrentPhoneDialCount+"',stringfield5 = '"+smstext+"',CallEndTime = '"+CallEndTime+"' where Sms_guid = '" + Sms_guid + "'and Phone1 = '"+phone+"'";
							log.debug("result=1处理SQL:" + updateRecord.toString());
							eliteBean.update(updateRecord, "dataSource");
							}else if (result == "2") {
								def updateRecord = "update T_IVROBRecord set status = 5,OBResult = '5000',CurrentPhoneDialCount = '"+CurrentPhoneDialCount+"',stringfield5 = '"+smstext+"' where Sms_guid = '" + Sms_guid + "'and Phone1 = '"+phone+"'";
								log.debug("result=2处理SQL:" + updateRecord.toString());
								eliteBean.update(updateRecord, "dataSource");					
							}else if (result == "-1") {
								def updateRecord = "update T_IVROBRecord set status = 5,OBResult = '5000',CurrentPhoneDialCount = '"+CurrentPhoneDialCount+"',stringfield5 = '"+smstext+"' where Sms_guid = '" + Sms_guid + "'and Phone1 = '"+phone+"'";
								log.debug("result=-1处理SQL:" + updateRecord.toString());
								eliteBean.update(updateRecord, "dataSource");					
							}
					}else if(Type == "A00012") {
						if(result == "1") {
							def updateRecord = "update T_IVROBRecord_AAA set status = 2,OBResult = '3001',CurrentPhoneDialCount = '"+CurrentPhoneDialCount+"',stringfield5 = '"+smstext+"',CallEndTime = '"+CallEndTime+"' where Sms_guid = '" + Sms_guid + "'and Phone1 = '"+phone+"'";
							log.debug("result=1处理SQL:" + updateRecord.toString());
							eliteBean.update(updateRecord, "dataSource");
							}else if (result == "2"|| result == "-1") {
								def updateRecord = "update T_IVROBRecord_AAA set status = 5,OBResult = '5000',CurrentPhoneDialCount = '"+CurrentPhoneDialCount+"',stringfield5 = '"+smstext+"' where Sms_guid = '" + Sms_guid + "'and Phone1 = '"+phone+"'";
								log.debug("result=2处理SQL:" + updateRecord.toString());
								eliteBean.update(updateRecord, "dataSource");
							}else if (result == "-1") {
								def updateRecord = "update T_IVROBRecord_AAA set status = 5,OBResult = '5000',CurrentPhoneDialCount = '"+CurrentPhoneDialCount+"',stringfield5 = '"+smstext+"' where Sms_guid = '" + Sms_guid + "'and Phone1 = '"+phone+"'";
								log.debug("result=-1处理SQL:" + updateRecord.toString());
								eliteBean.update(updateRecord, "dataSource");
							}
					}
					def updateIdCode = "Update T_IVROBLog_New set result = '" + result +"',result1 = '"+result1+"',result1code='"+result1code+"',firsttime='"+firsttime+"',result2='"+result2+"',result2code='"+result2code+"',secondtime='"+secondtime+"',result3='"+result3+"',result3code='"+result3code+"',thirdtime='"+thirdtime+"' where Sms_guid = '" + Sms_guid + "'and Tel = '"+phone+"' and Id = '"+obid+"'";
					log.debug("T_IVROBLog_New处理SQL:" + updateIdCode.toString());
					eliteBean.update(updateIdCode, "dataSource");		

				}else if(result == "0") {
					
					long endTime = System.currentTimeMillis();
					//包装拼接返回JSONObject
					reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"获取IVR外呼任务结果获取失败，任务未呼出，使用时长(毫秒):" + (endTime - startTime) + "\",\"data\":"+jsonBack+"}";
				}
			}
			
			def updatefailCode = "Update T_IVROBLog_New set result = '99' where 1=1 AND result IS  NULL AND Id = '"+obid+"'";
			log.debug("updatefailCode处理SQL:" + updatefailCode.toString());
			eliteBean.update(updatefailCode, "dataSource");	
			long endTime = System.currentTimeMillis();
			//包装拼接返回JSONObject
			reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"获取IVR外呼任务结果获取成功，使用时长(毫秒):" + (endTime - startTime) + "\",\"data\":"+jsonBack+"}";

		} catch (JSONException e) {
			long endTime = System.currentTimeMillis();
			reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"获取IVR外呼任务结果获取失败(" + e.getMessage() + "),使用时长(毫秒):" + (endTime - startTime) + "\",\"data\":{}}";
		}

		return reJson;
	}
}